package com.steam.xbcc.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.steam.xbcc.domain.MessageSms;
import com.steam.xbcc.dto.CourseOnlineSendMessageDto;
import com.steam.xbcc.service.IMessageSmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

import static com.steam.xbcc.constants.MqConstants.*;

@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup="course-sms-consumer-group",
        topic = COURSE_SMS_TOPIC,
        selectorExpression=COURSE_SMS_TAG
)
public class CourseSmsConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageSmsService messageSmsService;

    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        if (body == null || body.length == 0){
            return;
        }
        String str = new String(body, StandardCharsets.UTF_8);
        CourseOnlineSendMessageDto courseOnlineSendMessageDto = JSON.parseObject(str, CourseOnlineSendMessageDto.class);

        log.info("短信发送成功！");

        saveMessageSms(courseOnlineSendMessageDto);
    }

    private void saveMessageSms(CourseOnlineSendMessageDto courseOnlineSendMessageDto) {
        MessageSms messageSms = new MessageSms();
        messageSms.setTitle(courseOnlineSendMessageDto.getTitle());
        messageSms.setContent(courseOnlineSendMessageDto.getContent());
        messageSms.setSendTime(new Date());
        courseOnlineSendMessageDto.getUserSendMessageDtos().forEach(e->{
            messageSms.setUserId(e.getUserId());
            messageSms.setPhone(e.getContact());
            messageSmsService.insert(messageSms);
        });
    }
}
